package com.library.bookmanagement.controller;

import com.github.pagehelper.Page;
import com.library.bookmanagement.entity.*;
import com.library.bookmanagement.service.UserService;
import com.library.bookmanagement.util.Constant;
import com.library.bookmanagement.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.xml.transform.Result;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author ：ZXM
 * @date ：Created in 2020/5/20 10:15
 * @description：用户个人中心
 */
@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
@ResponseBody
@RequestMapping("/user/selfInfo")
@Api(value = "用户个人中心Controller",tags = {"用户个人中心接口"})
public class UserSelfInfoController {

    @Autowired
    private UserService userService;

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;

    /**
    * @Description: 头像修改
    * @Param: [username, file]
    * @return: com.library.bookmanagement.util.ResultUtil<java.lang.String>
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @ApiOperation(value = "头像上传")
    @PostMapping("/upload/headImg")
    public ResultUtil<String> uploadHeadImg(
            @ApiParam(value = "用户名称",name = "username")
            @RequestParam(name = "username") String username,
            @ApiParam(value = "上传图片",name = "file")
            @RequestParam(name = "file")
                    MultipartFile file){
        if (file == null) {
            return ResultUtil.error().message("请选择要上传的图片");
        }
        if (file.getSize() > 1024 * 1024 * 10) {
            return ResultUtil.error().message("文件大小不能大于10M");
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return ResultUtil.error().message("请选择jpg,jpeg,gif,png格式的图片");
        }
        String savePath = UPLOAD_FOLDER;
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        //通过UUID生成唯一文件名
        String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
        try {
            //将文件保存指定目录
            file.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error().message("保存文件异常");
        }
        userService.editUserImg(username,filename);
        //返回文件名称
        return ResultUtil.ok().data(filename);
    }

    /**
    * @Description: 个人基本信息展示
    * @Param: [username]
    * @return: com.library.bookmanagement.util.ResultUtil<com.library.bookmanagement.entity.User>
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @ApiOperation("个人基本信息展示")
    @PostMapping("/basicInfo")
    public ResultUtil<User> basicInfo(
            @ApiParam(value = "用户名",name = "username")
            @RequestParam(name = "username")String username
    ){
        return userService.queryUserByName(username);
    }

    /**
     * @Description: 个人基本信息修改
     * @Param: [user]
     * @return: com.library.bookmanagement.util.ResultUtil
     * @Author: ZXM
     * @Date: 2020/6/10
     */
    @ApiOperation(value = "个人基本信息修改")
    @PostMapping("/basicInfo/edit")
    public ResultUtil edit(
            @ApiParam(value = "userJson对象",name = "user")
            @RequestBody User user
            ){
        return userService.editUserById(user);
    }

    /**
    * @Description: 密码修改
    * @Param: [userId, oldPassword, newPassword]
    * @return: com.library.bookmanagement.util.ResultUtil
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @ApiOperation("密码修改")
    @PostMapping("/passwordEdit")
    public ResultUtil passwordEdit(
            @ApiParam(value = "用户ID",name = "userId")
            @RequestParam(name = "userId") Integer userId,
            @ApiParam(value = "oldPasword")String oldPassword,
            @ApiParam(value = "新密码",name ="newPassword")
            @RequestParam(name = "newPassword") String newPassword
    ){
       return userService.editUserPassword(userId,oldPassword,newPassword);
    }


    /**
    * @Description:
    * @Param: [pageNum, userId]
    * @return: com.library.bookmanagement.util.ResultUtil<java.util.Map<java.lang.String,java.lang.Object>>
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @ApiOperation(value = "用户借阅记录")
    @GetMapping("/borrowedRecord")
    public ResultUtil<Map<String,Object>> borrowRecord(
            @ApiParam(value = "当前页数",name = "pageNum")
            @RequestParam(name = "pageNum") Integer pageNum,
            @ApiParam(value = "用户Id",name = "userId")
            @RequestParam(name = "userId") Integer userId
    ){
        return userService.queryReadListByUserId(pageNum,Constant.pageSize,userId);
    }

    /**
    * @Description: 用户预定中记录
    * @Param: [userId]
    * @return: com.library.bookmanagement.util.ResultUtil<java.util.List<com.library.bookmanagement.entity.Reserve>>
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @ApiOperation(value = "用户预定中记录")
    @GetMapping("/reserveBook")
    public ResultUtil<List<Reserve>> reserveBook(
            @ApiParam(value = "用户Id",name = "userId")
            @RequestParam(name = "userId") Integer userId
    ){
        return userService.queryReserveListByUserId(userId);
    }

    /**
    * @Description: 用户逾期记录
    * @Param: [userId]
    * @return: com.library.bookmanagement.util.ResultUtil<java.util.List<com.library.bookmanagement.entity.Overdue>>
    * @Author: ZXM
    * @Date: 2020/6/19
    */
    @ApiOperation(value = "用户逾期记录")
    @GetMapping("/overdueBook")
    public ResultUtil<List<Overdue>> overdueBook(
            @ApiParam(value = "用户Id",name = "userId")
            @RequestParam(name = "userId") Integer userId
    ){
        return userService.overdueListByUserId(userId);
    }

    /**
    * @Description: 用户逾期归还
    * @Param: [userId, bookId]
    * @return: com.library.bookmanagement.util.ResultUtil
    * @Author: ZXM
    * @Date: 2020/6/19
    */
    @ApiOperation(value = "用户逾期归还")
    @GetMapping("/backOverdueBook")
    public ResultUtil backOverdueBook(
            @ApiParam(value = "用户Id",name = "userId")
            @RequestParam(name = "userId") Integer userId,
            @ApiParam(value = "书籍Id",name = "bookId")
            @RequestParam(name = "bookId") Integer bookId
    ){
        ReaderKey overdueKey = new ReaderKey();
        overdueKey.setBookId(bookId);
        overdueKey.setUserId(userId);
        return userService.backOverdueBookByKey(overdueKey);
    }
}
